<?php

namespace App\Http\Controllers;

use App\Exceptions\InvalidRequestException;
use App\Models\OrderItem;
use App\Models\Product;
use App\Models\ProductSku;
use Illuminate\Http\Request;
use App\Models\Order;
use App\Models\Cate;


class ProductsController extends Controller
{

    // 我的订单
    public function my_orders(Request $request){

        $user = \Auth::guard('api')->user();

        $orders = Order::query()
        ->with(['items.product', 'items.productSku'])
        ->where('user_id', $user->id)
        ->orderBy('created_at', 'desc')
        ->paginate();

        return $orders;


    }


    // 创建订单

    public function create(Request $request){

        // 获取用户
        $user = \Auth::guard('api')->user();

        // 生成唯一订单编号;
        $no = $this->onlyosn();

        // 保存订单;
        $order = new Order();
        $order->no = $no;
        $order->user_id = $user->id;
        $order->address = $request->address;
        $order->total_amount = $request->total_amount;
        $order->save();

        // 保存订单商品子项;

        $items = json_decode($request->items,true);

        $totalAmount = 0;

        foreach($items as $data){

            // return $data['product_sku_id'];

            $sku  = ProductSku::find($data['product_sku_id']);
            // 创建一个 OrderItem 并直接与当前订单关联
            $item = $order->items()->make([
                'amount' => $data['amount'],
                'price'  => $sku->price,
            ]);

            $item->product()->associate($sku->product_id);
            $item->productSku()->associate($sku);
            $item->save();
            $totalAmount += $sku->price * $data['amount'];

        }

        $totalAmount = sprintf("%.2f",$totalAmount);


        // 更新订单总金额;
        $order->update(['total_amount' => $totalAmount]);

        // 将下单的商品从购物车中移除
        $skuIds = collect($items)->pluck('product_sku_id');
        $user->cartItems()->whereIn('product_sku_id', $skuIds)->delete();

        /*
        order_id    订单编号
        product_id  商品编号;
        product_sku_id 规格编号;
        amount   商品数量;
        price    价格;
        */

        return response()->json(['status'=>200,'msg'=>'订单保存成功','total_price'=>$totalAmount,'order_id'=>$no]);

    }

    private function onlyosn()
    {
        @date_default_timezone_set("PRC");
        $order_id_main = date('YmdHis') . rand(10000000, 99999999);
        //订单号码主体长度
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }
        //唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）
        $osn = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT); //生成唯一订单号
        return $osn;
    }


    // 商品详情
    public function home_detail(Request $request){

       $product = Product::find($request->id)[0];

       if(strlen($product->image)>6){
           $product->image = $this->getImgArr( $product->image);
        }else{
            $product->image = Array();
        }

        $product->skus = $this->getSkus($request->id);
        $product->price = $this->getSkuPrice($request->id);

       return $product;

    }

    private function getSkus($id){

        $skus = ProductSku::where('product_id',$id)->orderBy('id')->get();
        return $skus;

    }

    private function getSkuPrice($id){

        $sku = ProductSku::where('product_id',$id)->first();
        return $sku->price;

    }

    private function getImgArr($str){

        $imgArr = explode("&", $str);

        foreach($imgArr as $k=>$imgName){
            $imgArr[$k] =  config('app.upload').$imgName;
        }
        return $imgArr;

    }

    // 获取一级分类下的商品
    public function main_list(Request $request){

        //$houses = House::withTrashed()->paginate(5);
        $size = $request->size ? $request->size : 5;

        // 获取二级分类id数组;
        $pid = $request->pid;
        $subCates = Cate::where('pid',$pid)->get();
        $idArr = Array();
        foreach($subCates as $k=>$subCate){
           array_push($idArr,$subCate->id);
        }

        $products = Product:: whereIn('pid', $idArr)->orderBy("created_at","desc")->paginate($size);

        foreach($products as $k=>$product){

             $cover_img = strlen($product["image"])>6 ? $this->getCoverImg($product["image"]) :config('app.upload').'default.jpg';
             $products[$k]["cover_url"] = $cover_img;
             unset($products[$k]["image"]);

        }

        return $products;

     }

     // 获取我的子类id数组
     private function getMySubCates($pid){
        $cates = Cate::where('pid',$pid)->get();
        return $cates;
     }

    // 获取二级分类下的商品
      public function sub_list(Request $request){

        //$houses = House::withTrashed()->paginate(5);
        $size = $request->size ? $request->size : 5;
        $products = Product::where('pid',$request->pid)->orderBy("created_at","desc")->paginate($size);

        foreach($products as $k=>$product){

             $cover_img = strlen($product["image"])>6 ? $this->getCoverImg($product["image"]) :config('app.upload').'default.jpg';
             $products[$k]["cover_url"] = $cover_img;
             unset($products[$k]["image"]);

        }

        return $products;

     }

    // 根据商品id获取sku默认第一个价格;
    private function getPrice($id){
        $skus = ProductSku::where('product_id',$id)->orderBy('id')->get();
        return $skus[0]['price'];
    }

       //图片字符串转数组
    private  function getCoverImg($str){
        $imgArr = explode("&", $str);
        return config('app.upload').'s_'.$imgArr[0]; // 默认第一张图片为封面图片;
    }


    public function index(Request $request)
    {
        // 创建一个查询构造器
        $builder = Product::query()->where('on_sale', true);
        // 判断是否有提交 search 参数，如果有就赋值给 $search 变量
        // search 参数用来模糊搜索商品
        if ($search = $request->input('search', '')) {
            $like = '%'.$search.'%';
            // 模糊搜索商品标题、商品详情、SKU 标题、SKU描述
            $builder->where(function ($query) use ($like) {
                $query->where('title', 'like', $like)
                    ->orWhere('description', 'like', $like)
                    ->orWhereHas('skus', function ($query) use ($like) {
                        $query->where('title', 'like', $like)
                            ->orWhere('description', 'like', $like);
                    });
            });
        }

        // 是否有提交 order 参数，如果有就赋值给 $order 变量
        // order 参数用来控制商品的排序规则
        if ($order = $request->input('order', '')) {
            // 是否是以 _asc 或者 _desc 结尾
            if (preg_match('/^(.+)_(asc|desc)$/', $order, $m)) {
                // 如果字符串的开头是这 3 个字符串之一，说明是一个合法的排序值
                if (in_array($m[1], ['price', 'sold_count', 'rating'])) {
                    // 根据传入的排序值来构造排序参数
                    $builder->orderBy($m[1], $m[2]);
                }
            }
        }

        $products = $builder->paginate(16);

        return view('products.index', [
            'products' => $products,
            'filters'  => [
                'search' => $search,
                'order'  => $order,
            ],
        ]);
    }

    public function show(Product $product, Request $request)
    {
        // 判断商品是否已经上架，如果没有上架则抛出异常。
        if (!$product->on_sale) {
            throw new InvalidRequestException('商品未上架');
        }

        $favored = false;
        // 用户未登录时返回的是 null，已登录时返回的是对应的用户对象
        if($user = $request->user()) {
            // 从当前用户已收藏的商品中搜索 id 为当前商品 id 的商品
            // boolval() 函数用于把值转为布尔值
            $favored = boolval($user->favoriteProducts()->find($product->id));
        }

        $reviews = OrderItem::query()
            ->with(['order.user', 'productSku']) // 预先加载关联关系
            ->where('product_id', $product->id)
            ->whereNotNull('reviewed_at') // 筛选出已评价的
            ->orderBy('reviewed_at', 'desc') // 按评价时间倒序
            ->limit(10) // 取出 10 条
            ->get();

        return view('products.show', [
            'product' => $product,
            'favored' => $favored,
            'reviews' => $reviews
        ]);
    }

    public function favor(Product $product, Request $request)
    {
        $user = $request->user();
        if ($user->favoriteProducts()->find($product->id)) {
            return [];
        }

        $user->favoriteProducts()->attach($product);

        return [];
    }

    public function disfavor(Product $product, Request $request)
    {
        $user = $request->user();
        $user->favoriteProducts()->detach($product);

        return [];
    }

    public function favorites(Request $request)
    {
        $products = $request->user()->favoriteProducts()->paginate(16);

        return view('products.favorites', ['products' => $products]);
    }

}
